<template>
  <div class="questionnaire-template-container">
    <div class="page-header">
      <h2>问卷模板管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateTemplate" icon="Plus">新建模板</el-button>
        <el-button type="info" @click="navigateToUserSubmissions" icon="Document">用户提交记录</el-button>
        <el-button @click="refreshData" :loading="loading" icon="Refresh">刷新</el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-card>
        <div class="filter-form">
          <el-form :inline="true" :model="queryParams" class="demo-form-inline">
            <el-form-item label="关键词">
              <el-input
                v-model="queryParams.keyword"
                placeholder="请输入标题关键词"
                clearable
                style="width: 220px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>

    <!-- 列表区域 -->
    <div class="template-list-content">
      <el-card v-loading="loading">
        <template #header>
          <div class="card-header">
            <span>问卷模板列表</span>
          </div>
        </template>

        <el-table :data="templateList" border style="width: 100%" row-key="id">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="问卷标题" min-width="180" show-overflow-tooltip />
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="creatorName" label="创建人" width="120" show-overflow-tooltip />
          <el-table-column prop="createdAt" label="创建时间" width="160" show-overflow-tooltip />
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="scope">
              <el-button-group>
                <el-button 
                  size="small"
                  type="primary"
                  @click="handleViewTemplate(scope.row)"
                >
                  预览
                </el-button>
                <el-button
                  size="small"
                  type="success"
                  @click="handleEditTemplate(scope.row)"
                  :disabled="!canEdit(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDeleteTemplate(scope.row)"
                  :disabled="!canDelete(scope.row)"
                >
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:currentPage="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="问卷预览"
      width="700px"
      destroy-on-close
    >
      <div v-if="currentTemplate" class="preview-container">
        <h2 class="preview-title">{{ currentTemplate.title }}</h2>
        <p class="preview-description">{{ currentTemplate.description }}</p>

        <div v-if="currentTemplate.questions && currentTemplate.questions.length > 0" class="questions-list">
          <div 
            v-for="(question, index) in currentTemplate.questions" 
            :key="index" 
            class="question-item"
          >
            <div class="question-header">
              <span class="question-index">{{ index + 1 }}</span>
              <span class="question-text">{{ question.questionText }}</span>
              <span v-if="question.isRequired" class="required-mark">*</span>
            </div>

            <!-- 单选题 -->
            <div v-if="question.questionType === 'single'" class="question-options">
              <el-radio-group v-model="previewAnswers[index]">
                <div v-for="(option, optionIndex) in question.options" :key="optionIndex" class="option-item">
                  <el-radio :label="option">{{ option }}</el-radio>
                </div>
              </el-radio-group>
            </div>

            <!-- 多选题 -->
            <div v-else-if="question.questionType === 'multiple'" class="question-options">
              <el-checkbox-group v-model="previewAnswers[index]">
                <div v-for="(option, optionIndex) in question.options" :key="optionIndex" class="option-item">
                  <el-checkbox :label="option">{{ option }}</el-checkbox>
                </div>
              </el-checkbox-group>
            </div>

            <!-- 文本题 -->
            <div v-else-if="question.questionType === 'text'" class="question-options">
              <el-input
                v-model="previewAnswers[index]"
                type="textarea"
                :rows="3"
                placeholder="请输入您的回答"
              />
            </div>
          </div>
        </div>

        <div v-else class="empty-questions">
          <el-empty description="该问卷暂无题目" />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handlePreviewSubmit">预览提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/user'
import { 
  getQuestionnaireTemplates, 
  getQuestionnaireTemplate,
  deleteQuestionnaireTemplate 
} from '@/api/questionnaire'

const router = useRouter()
const userStore = useUserStore()

// 用户权限判断
const isAdmin = computed(() => userStore.role === 'admin')
const userId = computed(() => userStore.userId)

// 加载状态
const loading = ref(false)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: ''
})

// 模板列表
const templateList = ref([])
const total = ref(0)

// 预览对话框
const previewDialogVisible = ref(false)
const currentTemplate = ref(null)
const previewAnswers = ref([])

// 页面初始化
onMounted(() => {
  fetchTemplateList()
})

// 导航到用户问卷提交记录页面
const navigateToUserSubmissions = () => {
  router.push('/questionnaire/user-submissions')
}

// 获取问卷模板列表
const fetchTemplateList = async () => {
  loading.value = true
  try {
    const res = await getQuestionnaireTemplates(queryParams)
    if (res.code === 200) {
      templateList.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取问卷模板列表失败')
    }
  } catch (error) {
    console.error('获取问卷模板列表出错:', error)
    ElMessage.error('获取问卷模板列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchTemplateList()
}

// 重置查询
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.pageNum = 1
  fetchTemplateList()
}

// 刷新数据
const refreshData = () => {
  fetchTemplateList()
}

// 新建模板
const handleCreateTemplate = () => {
  router.push('/questionnaire/template-edit')
}

// 查看模板
const handleViewTemplate = async (row) => {
  try {
    loading.value = true
    const res = await getQuestionnaireTemplate(row.id)
    if (res.code === 200) {
      currentTemplate.value = res.data
      previewAnswers.value = new Array(res.data.questions.length).fill(null).map(() => [])
      previewDialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取问卷模板详情失败')
    }
  } catch (error) {
    console.error('获取问卷模板详情出错:', error)
    ElMessage.error('获取问卷模板详情失败')
  } finally {
    loading.value = false
  }
}

// 编辑模板
const handleEditTemplate = (row) => {
  console.log('编辑模板，ID:', row.id)
  router.push(`/questionnaire/template-edit/${row.id}`)
}

// 删除模板
const handleDeleteTemplate = (row) => {
  ElMessageBox.confirm(
    `确定要删除模板"${row.title}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        loading.value = true
        const res = await deleteQuestionnaireTemplate(row.id)
        if (res.code === 200) {
          ElMessage.success('删除模板成功')
          fetchTemplateList()
        } else {
          ElMessage.error(res.msg || '删除模板失败')
        }
      } catch (error) {
        console.error('删除模板出错:', error)
        ElMessage.error('删除模板失败')
      } finally {
        loading.value = false
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 预览提交
const handlePreviewSubmit = () => {
  // 判断必填项是否已填写
  const template = currentTemplate.value
  if (!template || !template.questions) return

  const emptyRequired = template.questions.findIndex((q, index) => {
    if (!q.isRequired) return false

    const answer = previewAnswers.value[index]
    if (q.questionType === 'single' || q.questionType === 'text') {
      return !answer
    } else if (q.questionType === 'multiple') {
      return !answer || answer.length === 0
    }
    return false
  })

  if (emptyRequired !== -1) {
    ElMessage.warning(`第 ${emptyRequired + 1} 题是必填项，请填写完整`)
    return
  }

  ElMessage.success('预览问卷提交成功')
  previewDialogVisible.value = false
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchTemplateList()
}

// 页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchTemplateList()
}

// 判断当前用户是否可以编辑模板
const canEdit = (row) => {
  // 管理员或创建者可以编辑
  return isAdmin.value || row.createdById === userId.value
}

// 判断当前用户是否可以删除模板
const canDelete = (row) => {
  // 只有管理员可以删除
  return isAdmin.value
}
</script>

<style scoped>
.questionnaire-template-container {
  animation: fadeIn 0.3s ease-out;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: var(--card-background);
  padding: 20px 24px;
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: var(--text-primary);
  display: flex;
  align-items: center;
}

.page-header h2::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 20px;
  background: linear-gradient(180deg, var(--primary-color), #4d7aff);
  margin-right: 12px;
  border-radius: 2px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.template-list-content {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: 500;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 预览样式 */
.preview-container {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.preview-title {
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 12px;
}

.preview-description {
  font-size: 14px;
  color: #666;
  text-align: center;
  margin-bottom: 24px;
}

.questions-list {
  margin-top: 20px;
}

.question-item {
  margin-bottom: 24px;
  padding: 16px;
  border-radius: 8px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.question-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
}

.question-index {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background-color: var(--primary-color);
  color: white;
  border-radius: 50%;
  font-size: 14px;
  margin-right: 8px;
  flex-shrink: 0;
}

.question-text {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  flex: 1;
}

.required-mark {
  color: #f56c6c;
  margin-left: 4px;
}

.question-options {
  padding-left: 32px;
}

.option-item {
  margin-bottom: 8px;
}

.empty-questions {
  text-align: center;
  padding: 30px 0;
}

@media (max-width: 768px) {
  .filter-form {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }
}
</style> 